create 
--alter 
proc usp_HuyDH_UpdateSLMA
@madh varchar(6), @res int output
as
begin tran
	--set tran isolation level Serializable
	declare  @sl int, @slhuy int
	set @slhuy = (select SL from CTDONHANG 
				where MaDH = @madh)
	set @sl = (select SLMA from MONAN --with (xlock) 
				where MaMA in (select MaMA from CTDONHANG 
											where MaDH=@madh))
	waitfor delay '0:0:10'
	begin try
			set @sl = @sl + @slhuy
			
			if exists(select MaMA from CTDONHANG C, LICHGIAO L where C.MaDH = @madh and 
				  C.MaDH = L.MaDH  and DateDiff(day,GetDate(),L.NgayGioGH ) >= 0)
			begin 	  
				update MONAN 
				set SLMA = @sl
				where MaMA in (select MaMA from CTDONHANG  where MaDH = @madh)
				
				--select * from MONAN
				set @res = 1
			end
			else
			begin
				set @res = 0
			end
	end try
	begin catch 
		declare @ErrorMsg varchar(2000)
		select @ErrorMsg = N'Loi: ' + ERROR_MESSAGE()
		raiserror(@ErrorMsg, 16,1)
		rollback tran
		return	
	end catch
commit tran


Declare @res int
EXEC usp_HuyDH_UpdateSLMA 'DH022',@res output
print @res

select * from MONAN

select SLMA from MONAN where MaMA in
									(select MaMA from CTDONHANG 
									where MaDH = 'DH022')
select MaMA from CTDONHANG C, LICHGIAO L where C.MaDH = 'DH015' and 
				  C.MaDH = L.MaDH  and getdate() = ngaygioGH
				
				
				
				
				select * from monan where mama in (select * from lichgiao l, donhang d , ctdonhang c
									where ngaygioGH >= ngaygioDH and l.madh = d.madh and c.madh = d.madh )
				
				select * from lichgiao where DateDiff(day,GetDate(),NgayGioGH ) > 0